package com.hulk.dryad.manage.security.component;


import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.manage.security.util.SecurityMessageSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hulk
 * @version 1.0
 * @date 2021/3/16 17:05
 */
@Slf4j
public class DryadAccessDeniedHandler extends AccessDeniedHandlerImpl {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {
		if (response.isCommitted()) {
			return;
		}
		response.setCharacterEncoding(CommonConstants.UTF8);
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		response.setStatus(HttpStatus.FORBIDDEN.value());
		R<Object> result = accessDenied2R(e);
		WebUtils.renderJson(response,result);
	}

	public static R<Object> accessDenied2R(AccessDeniedException e) {
		// 没有权限 403
		int errCode = BEC.E_4003.getErrCode();
		String key = "AbstractAccessDecisionManager.accessDenied";
		String message = e.getMessage();
		Object[]  arg1 = { message } ;
		log.error("拒绝授权异常信息 :[{}]",message);
		String errmsg =	SecurityMessageSourceUtil.getAccessor().getMessage(key, arg1,"Access is denied");
		R<Object> result = R.failed(errCode,errmsg,message);
		return result;
	}
}
